package org.batatasframework.support.searchable.internal;

import org.batatasframework.support.database.jdbc.ConnectionAccessor;
import org.batatasframework.support.database.jdbc.DatabaseAccessor;
import org.batatasframework.support.database.metadatas.DatabaseMetadataResource;
import org.batatasframework.support.database.metadatas.TableMetadata;
import org.batatasframework.support.event.SearchableRequest;
import org.batatasframework.support.factory.AbstractPlatform;
import org.batatasframework.support.factory.TableDefinitionFactory;
import org.batatasframework.support.searchable.SearchableHandler;
import org.batatasframework.support.searchable.SearchablePlatform;

/**
 * 处理所有的查询和统计
 * 
 * <pre>
 * 进行查询处理的时候，位置很重要
 * </pre>
 * @author jackson
 *
 */
public class StandardSearchablePlatform extends AbstractPlatform implements SearchablePlatform{
	
	public StandardSearchablePlatform(TableDefinitionFactory tableFactory,
			DatabaseMetadataResource databaseMetadataSources) {
		super(tableFactory, databaseMetadataSources);
	}

	@Override
	public SearchableHandler buildSearchableHandler(SearchableRequest searchableConfigurable) throws Exception {

		DatabaseAccessor databaseAccessor = null;
		if(null == searchableConfigurable.getConnectionAccessor()){
			databaseAccessor = tableFactory.buildDatabaseAccessor();
			searchableConfigurable.setConnectionAccessor(databaseAccessor);
		}
		
		ConnectionAccessor connectionAccessor = searchableConfigurable.getConnectionAccessor();
		
		/*
		 * 如果使用定义的方式，这里不应该直接去访问数据库databaseMetadataSources对象
		 */
		TableMetadata tableMetadata = searchableConfigurable.getTableMetadata();
		if(null == tableMetadata){
			tableMetadata = databaseMetadataSources.loadTableMetadata(connectionAccessor, searchableConfigurable.getTableInfo());
		}
		
		return new StandardSearchableHandler(databaseMetadataSources, searchableConfigurable, tableMetadata, databaseAccessor);
	}
}
